<template>
  <div class="movie-detail-container">
    <div v-if="loading" class="loading-spinner">
      <div class="spinner"></div>
      加载中...
    </div>
    
    <div v-else-if="movie" class="movie-detail">
      <div class="movie-header">
        <div class="poster">
          <img :src="movie.poster || '/placeholder.jpg'" :alt="movie.title">
        </div>
        <div class="info">
          <h1>{{ movie.title || '未命名电影' }}</h1>
          <div class="meta">
            <span class="rating">{{ movie.rating ? `${movie.rating}/10` : '暂无评分' }}</span>
            <span class="year">{{ movie.year || '年份未知' }}</span>
            <span class="duration">{{ movie.duration || 0 }}分钟</span>
            <span class="category">{{ movie.category || '未分类' }}</span>
          </div>
          <p class="director">导演: {{ movie.director || '未知' }}</p>
          <p class="actors">主演: {{ movie.actors || '未知' }}</p>
          <div class="actions">
            <button 
              v-if="authStore.user" 
              @click="showCommentForm = !showCommentForm" 
              class="btn"
            >
              {{ showCommentForm ? '取消评论' : '发表评论' }}
            </button>
          </div>
        </div>
      </div>
      
      <div class="movie-description">
        <h2>剧情简介</h2>
        <p>{{ movie.description || '暂无简介' }}</p>
      </div>
      
      <div v-if="showCommentForm" class="comment-form">
        <h2>发表评论</h2>
        <textarea 
            v-model="commentContent" 
            placeholder="写下你的观后感..."
            :disabled="commentLoading"
        ></textarea>
        <button 
            @click="submitComment" 
            class="submit-btn"
            :disabled="!commentContent || commentLoading"
        >
            {{ commentLoading ? '提交中...' : '提交评论' }}
        </button>
        <p v-if="commentError" class="error-message">{{ commentError }}</p>
      </div>
      
      <div class="comments-section">
        <h2>用户评论</h2>
        <div v-if="comments.length === 0" class="no-comments">
          暂无评论
        </div>
        
        <div v-else class="comments-list">
          <div 
            v-for="comment in comments" 
            :key="comment.id" 
            class="comment"
          >
            <pre>{{ comment }}</pre>
            <div class="comment-header">
              <span class="username">{{ comment.user?.username || '匿名用户' }}</span>
              <span class="date">{{ formatDate(comment.createdAt) }}</span>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
          </div>
        </div>

      </div>
    </div>
    
    <div v-else class="not-found">
      <h2>电影未找到</h2>
      <router-link to="/movies" class="btn">返回电影列表</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import api from '@/services/api'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const movie = ref(null)
const comments = ref([])
const loading = ref(true)
const showCommentForm = ref(true); // 修改初始值为 true
const commentContent = ref('')
const commentLoading = ref(false)
const commentError = ref(null)

const fetchMovie = async () => {
  try {
    loading.value = true
    const response = await api.getMovie(route.params.id)
    movie.value = response.data
    await fetchComments()
  } catch (error) {
    console.error('获取电影失败:', error)
  } finally {
    loading.value = false
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '未知时间';
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return '未知时间'; // 检查日期是否有效
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

const fetchComments = async () => {
  try {
    const response = await api.getComments(route.params.id);
    comments.value = response.data || [];
    console.log('Fetched comments:', comments.value);
  } catch (error) {
    console.error('获取评论失败:', error);
  }
}

const submitComment = async () => {
  try {
    if (!authStore.user?.id) {
      return router.push(`/login?redirect=/movies/${route.params.id}`)
    }

    commentLoading.value = true
    commentError.value = null

    await api.addComment({
      content: commentContent.value,
      movieId: route.params.id,
      userId: authStore.user.id
    })

    commentContent.value = ''
    showCommentForm.value = false
    await fetchComments()
  } catch (error) {
    commentError.value = error.message || '评论提交失败'
  } finally {
    commentLoading.value = false
  }
}

onMounted(fetchMovie)
</script>

<style scoped lang="scss">
@import '@/styles/movie-detail';
</style>